//app.js
var common = require("./common/common.js").common;

App({
    onLaunch: function(options) {
        var that = this;
        if (wx.canIUse("getUpdateManager")) {
            const updateManager = wx.getUpdateManager();
            if (updateManager) {
                updateManager.onCheckForUpdate(function(res) {
                    if (res.hasUpdate) {
                        updateManager.onUpdateReady(function() {
                            wx.showModal({
                                title: "更新提示",
                                content: "新版本已经准备好，是否重启应用？",
                                success: function(res) {
                                    if (res.confirm) {
                                        updateManager.applyUpdate();
                                    }
                                }
                            });
                        });
                        updateManager.onUpdateFailed(function() {
                            wx.showModal({
                                title: "已经有新版本了哟~",
                                content: "新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~"
                            });
                        });
                    }
                });
            }
        }
        that.load(options, "siteinfo.js");
    },
    // 监听domain属性
    watch: function(method) {
        var obj = this.globalData;
        Object.defineProperty(obj, "domain", {
            configurable: true,
            enumerable: true,
            set: function(value) {
                this._domain = value;
                method(value);
            },
            get: function() {
                return this._domain;
            }
        });
    },
    getDomain: function(options) {
        var that = this;
        wx.getLocation({
            type: "wgs84",
            success(res) {
                const latitude = res.latitude;
                const longitude = res.longitude;
                const speed = res.speed;
                const accuracy = res.accuracy;
                console.log(latitude);
                console.log(longitude);
                common.getAppBase().then(() => {
                    wx.request({
                        url: "https://apis.map.qq.com/ws/geocoder/v1/?location=" + latitude + "," + longitude,
                        method: "get",
                        data: {
                            key: that.data.appBase.location_key
                        },
                        success: function(res) {
                            if (res.data.result.address_component.city == "北京市") {
                                //北京市todo...
                                console.log("北京市");
                                that.load(options, "siteinfo.js");
                            } else if (res.data.result.address_component.city == "天津市") {
                                //天津市
                                that.load(options, "tianjin.js");
                            } else {
                                //其他城市
                                that.load(options, "siteinfo.js");
                            }
                        }
                    });
                });
            }
        });
    },
    onShow: function() {},
    onHide: function() {},
    onError: function() {},
    siteInfo: require("siteinfo.js"),
    util: "test",
    userinfo: function() {},
    globalData: {},
    load: function(options, sitejs) {
        let user_id = options.query.user_id || 0;
        if (options.path) {
            switch (options.path) {
              case "pages/index/index":
                var scene = decodeURIComponent(options.query.scene).split(":");
                var share_leader_id = scene[1];
                break;

              default:
            }
        }
        var that = this;
        var siteInfo = require(sitejs);
        var uniacid = siteInfo.uniacid;
        wx.getSystemInfo({
            success: function(res) {
                let modelmes = res.model;
                if (modelmes.search("iPhone X") != -1 || modelmes.search("iPhone 1") != -1) {
                    that.globalData.isIPX = 1;
                } else {
                    that.globalData.isIPX = 0;
                }
                that.globalData.statusBarHeight = res.statusBarHeight;
            }
        });
        // 登录
                wx.login({
            success: res => {
                if (res.code) {
                    //发起网络请求
                    wx.request({
                        url: that.globalData.domain + "wx/openid_get",
                        method: "post",
                        data: {
                            code: res.code,
                            user_id: user_id,
                            uniacid: uniacid,
                            leader_id_share: share_leader_id
                        },
                        success: function(res) {
                            let openid = res.data.extra.openid;
                            //返回openid
                                                        let warrant = res.data.extra.warrant === "yes" ? true : false;
                            let errmsg = res.data.extra.errmsg || false;
                            if (errmsg) {
                                wx.showModal({
                                    title: "登录失败",
                                    content: "小程序AppSecret不正确，请重置！"
                                });
                                return;
                            }
                            let is_new;
                            if (res.data.extra.warrant == "no" && res.data.extra.new_entry_style == 1) {
                                //新人和开启选择站点设置
                                is_new = 0;
                            } else {
                                is_new = 1;
                            }
                            let user = {
                                nickname: res.data.extra.nickname,
                                openid: res.data.extra.openid,
                                avatar: res.data.extra.img,
                                warrant: warrant,
                                uid: parseInt(res.data.extra.uid),
                                s_leader: res.data.extra.s_leader,
                                is_new: is_new
                            };
                            let cart_count = 0;
                            let cart = wx.getStorageSync("cart") || [];
                            for (var i = 0; i < cart.length; i++) {
                                cart_count += cart[i]["count"];
                            }
                            wx.setStorage({
                                key: "cart_count",
                                data: cart_count
                            });
                            wx.setStorage({
                                key: "user",
                                data: user
                            });
                            wx.setStorageSync("uniacid", res.data.extra.leader_uniacid);
                            that.globalData.user = user;
                            if (that.userInfoReadyCallback) {
                                console.log("没获取openid，进入回调");
                                that.userInfoReadyCallback(user);
                            }
                            const page = getCurrentPages().pop() || false;
                            if (page) {
                                page.setData({
                                    warrant: warrant
                                });
                            }
                        },
                        fail: function(res) {
                            if (res.errMsg == "request:fail url 对应的服务正式无效。") {
                                var errorImg = [];
                                errorImg.push(that.globalData.domain.slice(0, -10) + "img/error.png");
                                wx.previewImage({
                                    urls: errorImg
                                });
                                return false;
                            }
                            var notice = res.errMsg == "request:fail url not in domain list" ? "请添加" + url_str + "到您的小程序服务器域名中" : res.errMsg;
                            wx.showModal({
                                title: "提示",
                                content: notice,
                                showCancel: false
                            });
                        }
                    });
                } else {}
            }
        });
        // 获取用户信息
                wx.getSetting({
            success: res => {
                if (res.authSetting["scope.userInfo"]) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                    wx.getUserInfo({
                        success: res => {
                            // 可以将 res 发送给后台解码出 unionId
                            this.globalData.userInfo = res.userInfo;
                        }
                    });
                }
            }
        });
        var url = siteInfo.siteroot;
        var multiid = siteInfo.multiid;
        var url_str = url.match(/(https|http):\/\/.*?\//);
        var multiid = siteInfo.multiid;
        if (multiid == "sqtg") {
            that.globalData.domain = url_str[0] + "frontend/web/index.php/";
        } else {
            that.globalData.domain = url_str[0] + "addons/worldidc_sqtg/power/frontend/web/index.php/";
        }
        var domain_message = {
            domain: that.globalData.domain,
            timeStamp: Date.parse(new Date()),
            sitejs: sitejs
        };
        wx.setStorageSync("domain_message", domain_message);
        console.log("回调1" + that.domainCallback);
        if (that.domainCallback) {
            console.log("回调2");
            that.domainCallback(that.globalData.domain);
        }
    }
});